import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, message, Row, Spin, TreeSelect } from 'antd';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { history } from 'umi';
import { DesignModelAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { DesignManageContext } from '../mconfig';
import { getKeyRouter, getLevelZeroJson } from '@/utils';
import { modelAddService, modelEditService, treeloadMdicMapServuces } from '../services';
import _ from 'lodash';
import { filterTree, handleDutySearchList } from '../common/common';

export const UpdateTableModal: React.FC<DesignModelAPI.IUpdateTableModal> = ({ onClose, visible, checkRowObj }) => {
  /**
   * modal ref
   */
  const updateTableRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 表单 form
   */
  const [updateTableForm] = Form.useForm();

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (updateTableRef) {
      if (updateTableRef.current) {
        if (updateTableRef.current.onModalCancel) {
          updateTableRef.current.onModalCancel();
        }
      }
    }
  };

  const {
    typeSelectRow,
    dicFlowSelectRow,
    rightTableProps: { reloadTableData },
  } = useContext(DesignManageContext);

  /** 处理组织机构数据 */
  let orgDeptList: any[] = getLevelZeroJson();
  const dutyIdList = handleDutySearchList(filterTree(orgDeptList), 'text', 'id');
  useEffect(() => {
    console.log(dutyIdList, 'dutyIdList================dutyIdList');
  }, [dutyIdList]);
  /**
   * 编辑保存流程数据
   */
  const [editFlowList, setEditFlowList] = useState<any[]>([]);

  /**
   * 获取异步数据回调
   * @param res
   */
  const treeloadMdicMapCallback = (res: any) => {
    if (res && res?.msgFlag) {
      let [parentKey]: string[] = Object.keys(res?.obj);
      let loadChildList: Record<string, any>[] = res?.obj?.[parentKey];
      let NewTreeData: Record<string, any>[] = handLoadDataList([typeSelectRow], parentKey, loadChildList, 'flowType');
      setEditFlowList(NewTreeData);
    } else {
      message.error(res?.msg);
    }
  };

  const { treeLoadMdicMapLoading, treeLoadMdicMapRun } = treeloadMdicMapServuces(treeloadMdicMapCallback);

  useEffect(() => {
    if (checkRowObj && checkRowObj?.id) {
      updateTableForm?.setFieldsValue({
        ...checkRowObj,
      });
      // treeLoadMdicMapRun(typeSelectRow?.flowType);
      treeLoadMdicMapRun({
        dicTypeIDs: typeSelectRow?.flowType,
      });
    }
  }, [checkRowObj, typeSelectRow]);

  /**
   * 处理异步数据
   * @param treeData 原有数据
   * @param parentKey 异步数据的 key
   * @param childList 异步的数据
   * @param selectKeys 异步数据的字段key
   */
  const handLoadDataList = (treeData: Record<string, any>[], parentKey: string, childList: Record<string, any>[], selectKeys: string) => {
    if (treeData?.length <= 0 || treeData == null || treeData == undefined) {
      return [];
    }
    treeData?.forEach((item, index) => {
      if (item?.[`${selectKeys}`] == parentKey) {
        treeData[index] = {
          ...item,
          children: childList,
        };
      }
    });
    return treeData;
  };

  /**
   * 随机生成流程标识
   * @param tableName
   * @returns
   */
  const keyWordMeno = useMemo(() => {
    let keyWord = typeSelectRow?.tableName;
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let seconds = date.getSeconds();
    let millisecond = date.getMilliseconds();
    keyWord = keyWord + year + month + day + hour + minute + seconds + millisecond;
    return keyWord;
  }, [typeSelectRow, dicFlowSelectRow]);

  /**
   * 处理树数据
   * @param data
   * @returns
   */
  const handleTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: item?.name,
        searchtitle: item?.name,
        key: item?.id,
        value: item?.id,
        children: item?.children && item?.children?.length > 0 ? handleTreeData(item?.children) : null,
        disabled: item?.tableName ? true : false,
      };
    });
  };

  /**
   * 新增编辑回调
   */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadTableData();
      if (res?.obj?.id) {
        history.push({
          pathname: `/activitiController/modelDesign/{modelId}/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            modelId: res?.obj?.id,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入新增接口
   */
  const { modelAddLoading, modelAddRun } = modelAddService(updateCallback);

  /**
   * 引入编辑接口
   */
  const { modelEditLoading, modelEditRun } = modelEditService(updateCallback);

  /**
   * 保存 流程数据
   */
  const modelSaveOnOK = () => {
    updateTableForm?.validateFields()?.then((values: any) => {
      if (checkRowObj && checkRowObj?.id) {
        let editPayload = {
          ...values,
          orderType: typeSelectRow?.orderType,
          category: typeSelectRow?.id,
          id: checkRowObj?.id,
          versionNum: checkRowObj?.versionNum,
        };
        modelEditRun(editPayload);
      } else {
        const dicFlowIdList = dicFlowSelectRow?.id ? dicFlowSelectRow?.id?.split('_') : '';
        let addPayload = {
          ...values,
          businessCategory: dicFlowSelectRow?.id ? dicFlowIdList?.[1] : '',
          orderType: typeSelectRow?.orderType,
          category: typeSelectRow?.id,
        };
        modelAddRun(addPayload);
      }
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateTableRef}
        title={checkRowObj && checkRowObj?.id ? '编辑流程' : '添加流程'}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
        onOk={modelSaveOnOK}
        confirmLoading={modelAddLoading || modelEditLoading || treeLoadMdicMapLoading}
      >
        <Spin spinning={modelAddLoading || modelEditLoading || treeLoadMdicMapLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={updateTableForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label={'流程名称'}
                    name="name"
                    rules={[
                      {
                        required: true,
                        message: '请输入流程名称',
                      },
                    ]}
                  >
                    <Input placeholder="请输入流程名称" allowClear />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label={'所属单位'}
                    name="ownCompanyID"
                    rules={[
                      {
                        required: true,
                        message: '请选择所属单位',
                      },
                    ]}
                  >
                    <TreeSelect
                      treeData={dutyIdList || []}
                      treeNodeFilterProp={'searchTitle'}
                      showSearch={true}
                      placeholder={'请选择所属单位'}
                      fieldNames={{ label: 'text' }}
                      disabled={checkRowObj && checkRowObj?.id}
                    />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label={'流程标识'} name="keyWord" initialValue={keyWordMeno}>
                    <Input placeholder="请输入流程标识" allowClear disabled />
                  </Form.Item>
                </Col>

                {checkRowObj && checkRowObj?.id && (
                  <Col span={24}>
                    <Form.Item
                      label={'流程类别'}
                      name="businessCategory"
                      rules={[
                        {
                          required: true,
                          message: '请选择流程类别',
                        },
                      ]}
                    >
                      <TreeSelect showSearch treeNodeFilterProp={'searchtitle'} placeholder="请选择流程类别" treeData={handleTreeData(editFlowList)} />
                    </Form.Item>
                  </Col>
                )}
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
